package com.cml.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.HystrixCircuitBreaker;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author cml
 * @create 2021/4/19 21:50
 */
@Service
public class PaymentService {

    /**
     * 正常访问
     * @param id
     * @return
     */
    //==============服务降级
    public String paymentInfo_ok(Integer id){
        return "线程池： "+Thread.currentThread().getName()+" paymentInfo_ok: "+id+"\t"+"哈哈哈";
    }

    @HystrixCommand(fallbackMethod = "paymentInfo_timeoutHandler",commandProperties={
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String paymentInfo_timeout(Integer id){
//        int time=5;
//        try {
//            TimeUnit.SECONDS.sleep(time);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        return "线程池： "+Thread.currentThread().getName()+" paymentInfo_timeout: "+id+"\t"+"耗时:"+time;
        return "计算结果：";
    }

    public String paymentInfo_timeoutHandler(Integer id){
        return "8001调用支付接口运行异常或错误\t"+"id:"+id+"\t+线程："+Thread.currentThread().getName();
    }

    //===============服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),  //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),   //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),  //时间范围
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), //失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(Integer id){
        if(id<0){
            throw new RuntimeException("*******id不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return "线程："+Thread.currentThread().getName()+"\t当前流水:"+serialNumber;
    }

    public String paymentCircuitBreaker_fallback(Integer id){
        return "id不能为负数:"+id;
    }

}
